<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/9/29
 * Time: 15:37
 * 特惠商品订单
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
class Orderh extends Base
{
    /**
     * 订单列表
     */
    public function index(){
        if(request()->isAjax ()){
            $keyword = trim(input('keyword'), ' '); // 订单号或ID
            $order_status = input('order_status');
            $is_pay = input('is_pay');
            $start_time = input('start_time');
            $end_time = input('end_time');
            $keyword_user = input('keyword_user');
            
            $where['order_del'] = 1;
            
            if(isset($keyword) && $keyword != ''){
                $where['order_id|order_number'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($keyword_user) && $keyword_user != ''){
                $where['user_real_name|user_phone'] = ['like', '%' . $keyword_user . '%'];
            }
            if(isset($order_status) && $order_status != ''){
                if($order_status != -1){
                    $where['order_status'] = $order_status;
                }
            }else{
                $where['order_status'] = 2;
            }
            if(isset($is_pay) && $is_pay != ''){
                $where['order_is_pay'] = $is_pay;
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['order_create_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['order_create_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['order_create_time'] = ['<=', $end_time];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_order')
                ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
                ->join('up_user_address', 'addr_id = order_addr_id', 'LEFT')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->where($where)
                ->count('order_id');
            $lists = Db::table('up_order')
                ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
                ->join('up_user_address', 'addr_id = order_addr_id', 'LEFT')
                ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
                ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
                ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
                ->field('order_id, order_number, order_is_pay, order_total_price, order_remark, order_status, 
                order_create_time, order_express_company, order_express_code, user_real_name, user_phone, 
                order_addr_id, u1.district sheng, u2.district shi, u3.district qu, addr_address, addr_user_name, 
                addr_user_phone, user_shop_name, order_cancel_reason, order_type, order_pay_type')
                ->where($where)
                ->order('order_create_time desc')
                ->page($Nowpage,$limits)
                ->select();
            foreach($lists as $k => $v){
                // 物流单号
                $lists[$k]['order_express_code'] = ltrim($v['order_express_code'], ',');
                // 收货地址
                $lists[$k]['address'] = $v['sheng'] . $v['shi'] . $v['qu'] . $v['addr_address'];
            }

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch();
    }
    
    /**
     * 商品列表
     * @return mixed|\think\response\Json
     */
    public function orderGoods(){
        if(Request::instance()->isAjax()){
            $where['oi_order_id'] = session('order_id');
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_order_info')
                ->join('up_goods', 'goods_id = oi_goods_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_order_info')
                ->join('up_goods', 'goods_id = oi_goods_id', 'LEFT')
                ->field('oi_goods_name, oi_goods_thumb, oi_goods_price, oi_num, oi_goods_spec, goods_type')
                ->where($where)
                ->order('oi_id asc')
                ->page($Nowpage,$limits)
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $order_id = input('order_id');
        if(isset($order_id) && $order_id != ''){
            session('order_id', $order_id);
        }
        $order = Db::table('up_order')
            ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
            ->join('up_user_address', 'addr_id = order_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('order_total_price, order_total_num, u1.district sheng, 
            u2.district shi, u3.district qu, addr_address, 
            addr_user_name, addr_user_phone')
            ->where('order_id', $order_id)
            ->find();
        return $this->fetch('orderh/ordergoods', ['order' => $order]);
    }
    
    /**
     * 取消订单
     * @return \think\response\Json
     */
    public function orderCancel(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $reason = input('reason');
            $order_goods = Db::table('up_order_info')->where('oi_order_id', $order_id)->field('oi_goods_id, oi_num')->select();
            $order = Db::table('up_order')
                ->where('order_id', $order_id)
                ->field('order_status, order_user_id, order_total_price')
                ->find();
    
            Db::startTrans();
            try{
                // 修改订单状态
                Db::table('up_order')
                    ->where('order_id', $order_id)
                    ->update([
                        'order_status' => 6,
                        'order_cancel_time' => date('Y-m-d H:i:s'),
                        'order_cancel_reason' => $reason
                    ]);
        
                foreach($order_goods as $k => $v){
                    // 释放库存
                    Db::table('up_goods')->where('goods_id', $v['oi_goods_id'])->setInc('goods_stock', $v['oi_num']);
                    // 减销量
                    $goods_num = Db::table('up_goods')->where('goods_id', $v['oi_goods_id'])->value('goods_sale_num');
                    if($goods_num > 0){
                        Db::table('up_goods')->where('goods_id', $v['oi_goods_id'])->setDec('goods_sale_num', $v['oi_num']);
                    }
                }
        
                // 如果是已支付订单，则退还积分&入积分明细
                if($order['order_status'] == 2){

                    $user = Db::table('up_u_user')->where('user_id', $order['order_user_id'])
                        ->field('user_recharge_balance')
                        ->find();

                    $desc = '取消订单退还';
                    if($reason){
                        $desc = $desc . '-' . $reason;
                    }

                    // 用户积分明细
                    $this->insertThInte($order['order_user_id'], 1, $desc, $order['order_total_price'], $user['user_recharge_balance'], $order_id);

                    // 用户积分
                    Db::table('up_u_user')
                        ->where('user_id', $order['order_user_id'])
                        ->inc('user_recharge_balance', $order['order_total_price'])
                        ->update();
                }
        
                Db::commit();
                return json(['code' => 200, 'msg' => '取消成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
        return $this->fetch('', ['order_id' => $order_id]);
        
        
    }
    
    /**
     * 发货
     * @return mixed|\think\response\Json
     */
    public function orderSend(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $order_express_company = trim(input('order_express_company'), ' ');
            $order_express_code = trim(input('order_express_code'), ' ');
            
            $express = [
                'order_express_company' => $order_express_company,
                'order_express_code' => ',' . $order_express_code,
                'order_status' => 3,
                'order_send_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_order')->where('order_id', $order_id)->update($express);
            if($res){
                return json(['code' => 200, 'msg' => '发货成功']);
            }else{
                return json(['code' => 100, 'msg' => '发货失败']);
            }
        }
        $wuliu = Db::table('up_about')->where('id', 7)->value('content');
        return $this->fetch('orderh/ordersend', ['order_id' => $order_id, 'wuliu' => $wuliu]);
    }
    
    /**
     * 确认收货
     * @return \think\response\Json
     */
    public function orderAffirm(){
        $order_id = input('id');
        $order_status = Db::table('up_order')->where('order_id', $order_id)->value('order_status');
        if($order_status != 3) return json(['code' => 100, 'msg' => '订单状态异常']);
        $res = Db::table('up_order')->where('order_id', $order_id)
            ->update(['order_status' => 4, 'order_over_time' => date('Y-m-d H:i:s')]);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 编辑物流信息
     * @return mixed|\think\response\Json
     */
    public function updateWuLiu(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $order_express_company = trim(input('order_express_company'), ' ');
            $order_express_code = trim(input('order_express_code'), ' ');
    
            $express = [
                'order_express_company' => $order_express_company,
                'order_express_code' => ',' . $order_express_code
            ];
            $res = Db::table('up_order')->where('order_id', $order_id)->update($express);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $wuliu = Db::table('up_order')->where('order_id', $order_id)->field('order_express_company, order_express_code')->find();
        $wuliu['order_express_code'] = trim($wuliu['order_express_code'], ',');
        return $this->fetch('orderh/updatewuliu', ['order_id' => $order_id, 'wuliu' => $wuliu]);
    }
    
    public function orderKuaiDi(){
        
    }
    
    /**
     * 编辑收货地址
     * @return mixed|\think\response\Json
     */
    public function orderAddress(){
        $order_id = input('order_id');
        if(Request::instance()->isPost()){
            $order_receive_username = input('order_receive_username');
            $order_receive_phone = input('order_receive_phone');
            $order_sheng = input('order_sheng');
            $order_shi = input('order_shi');
            $order_qu = input('order_qu');
            $order_address = input('order_address');
            
            $update = [
                'order_sheng' => $order_sheng,
                'order_shi' => $order_shi,
                'order_qu' => $order_qu,
                'order_address' => $order_address,
                'order_receive_username' => $order_receive_username,
                'order_receive_phone' => $order_receive_phone
            ];
            $res = Db::table('up_order')->where('order_id', $order_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        // 收货信息
        $address = Db::table('up_order')->where('order_id', $order_id)
            ->field('order_sheng, order_shi, order_qu, order_address, order_receive_username, 
            order_receive_phone')->find();
        // 省
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        // 市
        $city = Db::table('up_area')->where('pid', $address['order_sheng'])->field('district_id, district')->select();
        // 区
        $qu = Db::table('up_area')->where('pid', $address['order_shi'])->field('district_id, district')->select();
        $this->assign([
            'order_id' => $order_id,
            'address' => $address,
            'province' => $province,
            'city' => $city,
            'qu' => $qu
        ]);
        return $this->fetch('orderh/orderaddress');
    }


    /**
     * 导出
     * @return \think\response\Json
     */
    /*
    public function outExcel(){
        header('Access-Control-Allow-Origin:*');//允许所有来源访问

        $order_ids = input('ids');
        if($order_ids == ''){
            return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
        }
        $lists = Db::table('up_order')
            ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = order_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = order_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = order_qu', 'LEFT')
            ->join('up_area u4', 'u4.district_id = order_street', 'LEFT')
            ->field('order_id, order_number, order_is_pay, order_total_price, order_remark, order_status, 
                order_create_time, order_express_company, order_express_code, user_real_name, user_phone, 
                order_pay_time, order_send_time, order_over_time, order_cancel_time, 
                order_close_time, order_receive_username, order_receive_phone, 
                concat(u1.district, "", u2.district, "", u3.district, "", u4.district, "", order_address) address, user_shop_name')
            ->where('order_id', 'IN', $order_ids)
            ->order('order_create_time desc')
            ->select();
        // 商品
        $goods = Db::table('up_order_info')
            ->join('up_goods', 'oi_goods_id = goods_id', 'LEFT')
            ->where('oi_order_id', 'IN', $order_ids)
            ->field('goods_name, goods_spec, oi_num, oi_order_id')
            ->select();


        if($lists){
            foreach($lists as $k => $v){
                // 物流单号
                $lists[$k]['order_express_code'] = "\t". ltrim($v['order_express_code'], ',') ."\t";
                // 下单人手机号
                $lists[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";
                // 订单号
                $lists[$k]['order_number'] = "\t" . $v['order_number'] . "\t";
                // 总金额
                $lists[$k]['order_total_price'] = "\t" . $v['order_total_price'] . "\t";
                // 支付状态
                $lists[$k]['order_is_pay'] = $v['order_is_pay'] == 1 ? '未支付' : '已支付';
                // 订单状态
                switch($v['order_status']){
                    case 1:
                        $lists[$k]['order_status'] = '待付款';
                        break;
                    case 2:
                        $lists[$k]['order_status'] = '待发货';
                        break;
                    case 3:
                        $lists[$k]['order_status'] = '待收货';
                        break;
                    case 4:
                        $lists[$k]['order_status'] = '已完成';
                        break;
                    case 5:
                        $lists[$k]['order_status'] = '已关闭';
                        break;
                    case 6:
                        $lists[$k]['order_status'] = '已取消';
                        break;
                    default:
                        $lists[$k]['order_status'] = '未知';
                }

                $str = '';
                foreach($goods as $kk => $vv){
                    if($vv['oi_order_id'] == $v['order_id']){
                        $str .= "{$vv['goods_name']}--{$vv['goods_spec']}--{$vv['oi_num']}\n";
                    }
                }
                $lists[$k]['order_goods'] = rtrim($str, "\n");
            }
            // 表头数据数组
            $headArr = ['订单ID', '订单编号', '支付状态', '订单总金额', '备注', '订单状态', '下单时间', '快递公司',
                '快递单号', '下单用户', '下单手机号', '付款时间', '发货时间','收货时间', '取消时间', '关闭时间',
                '收货人', '收货人手机号', '收获地址', '店铺名称', '商品'];

            $res = exportExcel('Order', time(), $headArr, $lists);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
    */

    /**
     *
     * execl数据导出
     * @param string $name 表头信息
     * @param string $title 模型名（如Member），用于导出生成文件名的前缀
     * @param array $cellName 表头及字段名
     * @param array $data 导出的表数据
     */
    /*
    function exportExcel($file_name1, $file_name2, $title, $list)
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        $date = date('Ymd');
        $dir = ROOT_PATH . 'public' . DS . 'excel/' . $date;
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $file_name = $file_name1 . $file_name2 . '.csv';
        $path = ("{$dir}/".iconv('UTF-8','gb2312',$file_name));
        $file = fopen($path, 'w');
        $limit = 100000;
        $calc = 0;
        foreach ($title as $v){
            $tit[] = iconv('UTF-8', 'GB2312//IGNORE',$v);
        }
        fputcsv($file, $tit);
        foreach ($list as $v){
            $calc++;
            if($limit == $calc){
                ob_flush();
                flush();
                $calc = 0;
            }
        }
        unset($list);
        fclose($file);
        $filePath = 'excel/' . $date . '/' . $file_name;
        $result = array( 'code' => 200, 'msg' =>"/".$filePath );
        return $result;
    }
    */

    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $order_ids = input('ids');

        $where['order_del'] = 1;
        if($order_ids == -1){
            $keyword = trim(input('keyword'), ' '); // 订单号或ID
            $order_status = input('order_status');
            $is_pay = input('is_pay');
            $start_time = input('start_time');
            $end_time = input('end_time');
            $keyword_user = input('keyword_user');

            if(isset($keyword) && $keyword != ''){
                $where['order_id|order_number'] = ['like', '%' . $keyword . '%'];
            }
            if(isset($keyword_user) && $keyword_user != ''){
                $where['user_real_name|user_phone'] = ['like', '%' . $keyword_user . '%'];
            }
            if(isset($order_status) && $order_status != ''){
                if($order_status != -1){
                    $where['order_status'] = $order_status;
                }
            }else{
                $where['order_status'] = 2;
            }
            if(isset($is_pay) && $is_pay != ''){
                $where['order_is_pay'] = $is_pay;
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['order_create_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['order_create_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['order_create_time'] = ['<=', $end_time];
            }
        }else{
            if($order_ids == ''){
                return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
            }
            $where['order_id'] = ['IN', $order_ids];
        }

        $lists = Db::table('up_order')
            ->join('up_u_user', 'order_user_id = user_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = order_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = order_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = order_qu', 'LEFT')
            ->join('up_th_rule', 'order_th = rule_id', 'LEFT')
            ->field('order_id, order_number, order_is_pay, order_total_price, order_remark, order_status, 
                order_create_time, order_express_company, order_express_code, user_real_name, user_phone, 
                order_addr_id, order_pay_time, order_send_time, order_over_time, order_cancel_time, 
                order_close_time, order_receive_username, order_receive_phone, order_pay_type, order_type, order_goods_id, 
                concat(u1.district, "", u2.district, "", u3.district, "", order_address) address, user_shop_name, rule_name')
            ->where($where)
            ->order('order_create_time desc')
            ->select();
        // 商品
        $goods = Db::table('up_order_info')
            ->join('up_goods', 'oi_goods_id = goods_id', 'LEFT')
            ->where('oi_order_id', 'IN', $order_ids)
            ->field('goods_name, goods_spec, oi_num, oi_order_id')
            ->select();
        foreach($lists as $k => $v){
            // 物流单号
            $lists[$k]['order_express_code'] = "\t". ltrim($v['order_express_code'], ',') ."\t";
            // 下单人手机号
            $lists[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";
            // 订单号
            $lists[$k]['order_number'] = "\t" . $v['order_number'] . "\t";
            // 总金额
            $lists[$k]['order_total_price'] = "\t" . $v['order_total_price'] . "\t";
            // 支付状态
            $lists[$k]['order_is_pay'] = $v['order_is_pay'] == 1 ? '未支付' : '已支付';
            // 订单类型
            $lists[$k]['order_type'] = $v['order_type'] == 1 ? '普通订单' : '特惠礼包订单';
            // 支付类型
            $lists[$k]['order_pay_type'] = $v['order_pay_type'] == 1 ? '积分' : ($v['order_pay_type'] == 2 ? '微信' : '支付宝');
            // 订单状态
            switch($v['order_status']){
                case 1:
                    $lists[$k]['order_status'] = '待付款';
                    break;
                case 2:
                    $lists[$k]['order_status'] = '待发货';
                    break;
                case 3:
                    $lists[$k]['order_status'] = '待收货';
                    break;
                case 4:
                    $lists[$k]['order_status'] = '已完成';
                    break;
                case 5:
                    $lists[$k]['order_status'] = '已关闭';
                    break;
                case 6:
                    $lists[$k]['order_status'] = '已取消';
                    break;
                default:
                    $lists[$k]['order_status'] = '未知';
            }

            $str = '';
            foreach($goods as $kk => $vv){
                if($vv['oi_order_id'] == $v['order_id']){
                    $str .= "{$vv['goods_name']}--{$vv['goods_spec']}*{$vv['oi_num']}\n";
                }
            }
            $lists[$k]['order_goods'] = rtrim($str, "\n");
        }
        $cellname = [
            ['order_id', '订单ID', 10, 'LEFT'],
            ['order_number', '订单编号', 20, 'LEFT'],
            ['order_goods', '商品', 40, 'LEFT'],
            ['order_pay_type', '支付方式', 15, 'LEFT'],
            ['order_is_pay', '支付状态', 15, 'LEFT'],
            ['order_type', '订单类型', 15, 'LEFT'],
            ['rule_name', '福利权限', 15, 'LEFT'],
            ['order_total_price', '订单总金额', 15, 'LEFT'],
            ['order_status', '订单状态', 15, 'LEFT'],
            ['user_real_name', '下单用户', 15, 'LEFT'],
            ['user_phone', '下单手机号', 15, 'LEFT'],
            ['order_remark', '备注', 20, 'LEFT'],
            ['address', '收获地址', 30, 'LEFT'],
            ['order_receive_username', '收货人', 15, 'LEFT'],
            ['order_receive_phone', '收货人手机号', 15, 'LEFT'],
            ['user_shop_name', '店铺名称', 15, 'LEFT'],
            ['order_express_company', '快递公司', 15, 'LEFT'],
            ['order_express_code', '快递单号', 20, 'LEFT'],
            ['order_create_time', '下单时间', 20, 'LEFT'],
            ['order_pay_time', '付款时间', 20, 'LEFT'],
            ['order_send_time', '发货时间', 20, 'LEFT'],
            ['order_over_time', '收货时间', 20, 'LEFT'],
            ['order_cancel_time', '取消时间', 20, 'LEFT'],
            ['order_close_time', '关闭时间', 20, 'LEFT']
        ];
        $res = exportExcelZhy('订单', 'Order', $cellname, $lists);
        return json($res);
    }
}